package 聊天室练习.聊天室练习01;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private ServerSocket serverSocket;
    private Socket socket;
    private List<PrintWriter> pws = new ArrayList<>();
    private ExecutorService threatPool = Executors.newFixedThreadPool(4);

    public Server(){
        System.out.println("正在启动服务器");

        try {
            serverSocket = new ServerSocket(8088);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("服务器启动成功");
    }

    private void start(){
        try {
            while (true){
                System.out.println("等待客户端连接");
                socket = serverSocket.accept();
                System.out.println("客户端连接成功");
                ClientHandler clientHandler = new ClientHandler();
//                Thread t = new Thread(clientHandler);
//                t.start();
                threatPool.execute(clientHandler);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public class ClientHandler implements Runnable{
        private String host;

        public ClientHandler() {
            host = socket.getInetAddress().getHostName();
        }


        public void run(){
            PrintWriter pw = null;
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,"UTF-8");
                BufferedReader br = new BufferedReader(isr);


                OutputStream os = socket.getOutputStream();
                pw = new PrintWriter(os,true);
                synchronized (pws){
                    pws.add(pw);
                    for(PrintWriter p : pws){
                        p.println(this.host+"上线了");
                    }
                }

                String line;
                //阻塞
                while ((line = br.readLine()) != null){
                    System.out.println(this.host +"说："+line);
                    sendMessage(line);
                }
            } catch (IOException e) {
                System.out.println(this.host +"客户端异常断开了");;
            }finally {
                synchronized (pws){
                    pws.remove(pw);
                    for (PrintWriter p : pws ){
                        int clientCount = pws.size();
                        p.println(this.host + "断开了，" + "当前在线人数：" + clientCount);
                    }
                }

            }

        }

        private void sendMessage(String line){
            synchronized (pws){
                for (PrintWriter pw : pws){
                    pw.println(this.host +"说："+line);
                }
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
}

